package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import org.omg.PortableInterceptor.INACTIVE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * @PackageName: com.itheima.service.impl
 * @ClassName: RoleServiceImpl
 * @Author: LiLeNing
 * @Date: 2020/3/19 12:21
 * @Description:
 */
@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Override
    public List<Role> findAll() {
        return roleDao.findAll();
    }

    @Override
    public void add(Role role, Integer[] permissionIds, Integer[] menuIds) {
        //新增角色
        roleDao.add(role);
        Integer roleId = role.getId();
        //设置角色和权限多对多关系
        roleDao.setRoleAndPermission(roleId,permissionIds);
        //设置角色和菜单多对多关系
        roleDao.setRoleAndMenu(roleId,menuIds);
    }

    @Override
    public PageResult findPage(QueryPageBean pageBean) {
        Integer currentPage = pageBean.getCurrentPage();
        Integer pageSize = pageBean.getPageSize();
        String queryString = pageBean.getQueryString();
        //使用分页助手插件实现分页查询
        PageHelper.startPage(currentPage,pageSize);
        Page<Role> page = roleDao.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public Role findById(Integer id) {
        return roleDao.findById(id);
    }

    @Override
    public void edit(Role role, Integer[] permissionIds, Integer[] menuIds) {
        //编辑角色
        roleDao.edit(role);
        Integer roleId = role.getId();
        //删除角色和权限多对多关系
        roleDao.deleteAssociationPermission(roleId);
        //删除角色和菜单多对多关系
        roleDao.deleteAssociationMenu(roleId);
        //设置角色和权限多对多关系
        roleDao.setRoleAndPermission(roleId,permissionIds);
        //设置角色和菜单多对多关系
        roleDao.setRoleAndMenu(roleId,menuIds);
    }
    @Autowired

    private PermissionDao permissionDao;
    @Autowired

    private MenuDao menuDao;
    @Override
    public void delete(Integer roleId){
        List<Integer> permissionIds = permissionDao.findPermissionIdsByRoleId(roleId);
        if (permissionIds.size() > 0){
            roleDao.deleteAssociationPermission(roleId);
        }
        List<Integer> menuIds = menuDao.findMenuIdsByRoleId(roleId);
        if (menuIds.size() > 0){
            roleDao.deleteAssociationMenu(roleId);
        }
        roleDao.delete(roleId);
    }
}
